package io.renren.modules.app.controller;

import io.renren.common.utils.R;
import io.renren.modules.app.utils.GetUrlPic;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

//@Slf4j
@RestController
@RequestMapping("/app/file")
@Api(value = "文件操作",tags = "文件操作")
public class AppFileController {

    @Value("${file.path}")
    private String filePath;


    @PostMapping("/uploadImage")
    @ApiOperation("上传照片")
    public R uploadImage(@RequestParam(value = "file") MultipartFile file) throws RuntimeException {
        if (file.isEmpty()) {
            return R.error("文件不能为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
//        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
//        log.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
//        String filePath = fileP;
        // 解决中文问题，liunx下中文路径，图片显示问题
        String filePath = GetUrlPic.getFilePath(this.filePath)+"/";
        fileName = UUID.randomUUID().toString().replaceAll("-","") + suffixName;
        File dest = new File(this.filePath + filePath+fileName);
        try {
            file.transferTo(dest);
//            log.info("上传成功后的文件路径未：" + filePath+fileName);
            return R.ok().put(filePath+fileName);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("文件上传失败");
    }
//
//
    @GetMapping("/down/{picture}/{year}/{month}/{imageName}")
    @ApiOperation("下载照片")
    public void downloadImage(@PathVariable("picture") String picture, @PathVariable("year") String year, @PathVariable("month") String month,
                              @PathVariable("imageName") String imageName, HttpServletRequest request, HttpServletResponse response) {
        //String fileName = "123.JPG";
//        log.debug("the imageName is : " + imageName);
        String fileUrl = filePath + "/" + picture + "/" + year + "/" + month + "/" + imageName;
        if (fileUrl != null) {
            //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
           /* String realPath = request.getServletContext().getRealPath(
                    "//WEB-INF//");*/
            /*File file = new File(realPath, fileName);*/
            File file = new File(fileUrl);
//            imageName = imageName.substring(imageName.lastIndexOf("/"));
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + imageName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
//        return null;
    }
}
